<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title></title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport"
          content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=0">
    <link rel="stylesheet" href="/layui/css/layui.css" media="all">
    <link rel="stylesheet" href="/style/admin.css" media="all">
    <link rel="stylesheet" href="/style/edit-table.css" media="all"/>
</head>
<body>
<div class="layui-fluid">
    <div class="layui-row layui-col-space15">
        <div class="layui-col-md12">
            <div class="layui-card">
                <div class="layui-card-header">工具采购订单</div>
                <div class="layui-card-body">
                    <div style="margin-bottom: 10px;">
                        <div class="layui-input-item" style="float:left;padding-right:10px;">
                            <form class="layui-form layui-row layui-col-space16">
                                <div class="layui-col-md12">
                                    <div class="layui-form-item">
                                        <label class="layui-form-label">供应商</label>
                                        <div class="layui-input-block">
                                            <input type="text" id="supplier" placeholder="请输入供应商"
                                                   class="layui-input">
                                        </div>
                                    </div>
                                </div>
                            </form>
                        </div>
                        <div style="clear:both;"></div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <div class="layui-row layui-col-space15">
        <div class="layui-col-md12">
            <div class="layui-card">
                <div class="layui-card-header">采购订单明细</div>
                <div class="layui-card-body">
                    <div style="margin-bottom: 10px;">
                        <div>
                            <a id="add-btn" class="layui-btn">添加</a>
                            <a id="del-btn" class="layui-btn  layui-btn-danger">删除</a>
                            <a id="clear-btn" class="layui-btn layui-btn-primary">清空</a>
                        </div>
                        <div style="clear:both;"></div>
                    </div>
                    <table class="layui-hide" id="item-table"
                           lay-filter="item-table"></table>
                </div>
            </div>
        </div>
    </div>
    <div style="text-align: center;padding: 20px;">
        <a id="submit-btn" class="layui-btn">提交单据</a>
        <a id="save-btn" class="layui-btn layui-btn-primary">保存草稿</a>
        <a id="back-btn" class="layui-btn layui-btn-primary">返回</a>
    </div>

</div>

<script type="text/html" id="tool-tpl">
    <div class="layui-form">
        {{# }}
        <select lay-filter="tool" lay-search>
            <option value="">选择工具</option>
            {{# layui.each(groupedTools, function(group, items){ }}
            <optgroup label="{{=group}}">
                {{# layui.each(items, function(i, v){ }}
                <option value="{{= v.id }}" {{=v.id
                == d.toolId ? 'selected' : '' }} {{=v.disabled ? 'disabled' : '' }} >{{= v.name }} | {{= v.brand }}
                |
                {{= v.model }}</option>
                {{# }); }}
            </optgroup>
            {{# }); }}
        </select>
    </div>
</script>
<script type="text/html" id="quantity-tpl">
    <input type="number" class="layui-input quantity" min="0" value="{{= d.quantity}}" lay-verify="required">
</script>
<script type="text/html" id="note-tpl">
    <input type="text" class="layui-input note" value="{{= d.note}}">
</script>

<script src="/layui/layui.js"></script>
<script>
    var tools = [];//工具清单
    var groupedTools = {};//分组后的工具清单
    var toolMap;//工具清单hash表（根据ID快速查找）
    //业务单据健名
    const ORDER_KEY = 'tool-purchase-order';
    layui.config({
        base: '/' //静态资源所在路径
    }).extend({
        index: 'lib/index' //主入口模块
    }).use(['index', 'table', 'form', 'laydate'], function () {
        var $ = layui.$;
        var table = layui.table;
        var form = layui.form;

        //加载初始单据
        var orderData = JSON.parse(sessionStorage.getItem(ORDER_KEY) || '{}');
        //初始化单头
        $('#supplier').val(orderData.supplier);//供应商

        //加载工具库
        loadTools(function (data) {
            tools = data;
            groupedTools = tools.reduce((groups, tool) => {
                if (!groups[tool.typeText]) {
                    groups[tool.typeText] = [];
                }
                groups[tool.typeText].push(tool);
                return groups;
            }, {});
            toolMap = new Map(tools.map(item => [item.id, item]));
            //已在明细中的禁用
            if (orderData.items) {
                let toolIds = new Set(orderData.items.map(item => item.toolId));
                for (let tool of tools) {
                    if (toolIds.has(tool.id)) {
                        tool['disabled'] = true;
                    }
                }
            }
        });

        function loadTools(callback) {
            $.ajax({
                url: '/tools', // 你的请求URL
                type: 'GET',
                async: false, // 设置为同步请求
                success: function (result) {
                    if (callback) {
                        callback(result.data);
                    }
                },
                error: function (xhr, status, error) {
                    console.error(error);
                }
            });
        }

        table.render({
            elem: '#item-table',
            data: orderData.items || [{}],
            cols: [[
                {checkbox: true, fixed: true},
                {field: 'toolId', title: '选择工具', width: 250, templet: '#tool-tpl'},
                {field: 'name', width: 150, title: '工具名称'},
                {field: 'brand', width: 150, title: '品牌'},
                {field: 'model', width: 150, title: '型号/规格'},
                {field: 'unit', width: 100, title: '单位', align: 'center'},
                {field: 'quantity', width: 100, title: '数量', templet: '#quantity-tpl'},
                {field: 'note', title: '备注', templet: '#note-tpl'}
            ]],
            done: function (res, curr, count) {
                let options = this;
                let tableId = options.id;
                // 获取表格所有数据
                table.getTableData = function () {
                    return table.cache[tableId];
                };
                // 获取当前行数据
                table.getRowData = function (elem) {
                    let index = $(elem).closest('tr').data('index');
                    return table.cache[tableId][index] || {};
                };
                //将组件的值设置到数据模型
                table.setRowFieldValue = function (elem, field) {
                    let value = elem.val(); // 获取输入框的值
                    let rowData = table.getRowData(elem);
                    rowData[field] = value;
                }
                //添加一行
                table.addRow = function () {
                    let tableData = table.getTableData();
                    tableData.push({});
                    table.reloadData();
                }
                // 获取表格选中数据
                table.getCheckedData = function () {
                    let checkStatus = table.checkStatus(tableId);
                    return checkStatus.data;
                };
                // 重新加载数据
                table.reloadData = function (data) {
                    table.reload(tableId, {
                        data: data ? data : table.cache[tableId],
                    }, function (res) {
                        console.error(res);
                    });
                };

                //工具选择监听
                form.on('select(tool)', function (data) {
                    let elem = data.elem; // 获得 select 原始 DOM 对象
                    let value = data.value; // 获得被选中的值
                    let rowData = table.getRowData(elem); // 获取当前行数据(如 id 等字段，以作为数据修改的索引)
                    let preToolId = rowData['toolId'];//更改前的值
                    let preTool = toolMap.get(preToolId);
                    let toolId = parseInt(value);
                    rowData['toolId'] = toolId;
                    let tool = toolMap.get(toolId);
                    rowData['name'] = tool['name'];
                    rowData['brand'] = tool['brand'];
                    rowData['model'] = tool['model'];
                    rowData['unit'] = tool['unit'];
                    tool['disabled'] = true;
                    if (preTool) {
                        delete preTool['disabled'];
                    }
                    table.reload(tableId);
                });
                //数量
                $('.quantity').on('blur', function () {
                    table.setRowFieldValue($(this), 'quantity');
                });
                //备注
                $('.note').on('blur', function () {
                    table.setRowFieldValue($(this), 'note');
                });
            }
        });

        //添加明细
        $("#add-btn").on('click', function () {
            let tableData = table.getTableData();   //获取当前表格中数据
            let lastRow = tableData[tableData.length - 1];
            if (!lastRow.toolId) {
                layer.msg('请先完成当前行');
                return;
            }
            tableData.push({});
            table.reloadData();
        });

        //删除选中明细
        $("#del-btn").on('click', function () {
            let checkedData = table.getCheckedData();
            let tableData = table.getTableData();
            let toolIds = new Set(checkedData.map(item => item.toolId));
            for (let i = tableData.length - 1; i >= 0; i--) {
                if (tableData[i].toolId && toolIds.has(tableData[i].toolId)) {
                    let tool = toolMap.get(tableData[i].toolId);
                    delete tool['disabled'];
                    tableData.splice(i, 1);
                }
            }
            table.reloadData();
        });

        //清空明细
        $("#clear-btn").on('click', function () {
            layer.confirm('确定清空明细吗？', function (index) {
                clearItems();
                layer.close(index);
            });
        });

        $("#submit-btn").on('click', function () {
            let orderData = getOrderData();
            if (checkOrderData(orderData)) {
                $.ajax({
                    url: '/tool-purchase-orders',
                    type: 'PUT',
                    contentType: 'application/json',
                    data: JSON.stringify(orderData),
                    dataType: 'json', // 期望从服务器返回的数据类型
                    success: function (res) {
                        console.log(res);
                        if (res.code == 200) {
                            sessionStorage.removeItem(ORDER_KEY);
                            $('#supplier').val('');
                            clearItems();
                            layer.msg('单据已提交');
                        } else {
                            layer.msg(res.msg);
                        }
                    },
                    error: function (xhr, status, error) {
                        console.error('Error:', error);
                    }
                });
            }
        });

        $("#save-btn").on('click', function () {
            let orderData = getOrderData();
            sessionStorage.setItem(ORDER_KEY, JSON.stringify(orderData));
            layer.msg('单据已暂存');
        });

        $("#back-btn").on('click', function () {
            window.location.href = 'tool-purchase-order.html';
        });

        /**
         * 清空明细
         */
        function clearItems() {
            for (let tool of tools) {
                delete tool['disabled'];
            }
            table.reloadData([{}]);
        }

        /**
         * 获取单据数据
         * @returns {{}}
         */
        function getOrderData() {
            let orderData = {};
            let tableData = table.getTableData();
            let items = [];
            for (let data of tableData) {
                let item = Object.assign({}, data);
                delete item['LAY_TABLE_INDEX'];
                items.push(item);
            }
            orderData.items = items;
            orderData.supplier = $('#supplier').val();
            return orderData;
        }

        /**
         * 检查单据数据合法性
         * @param orderData
         * @returns {boolean}
         */
        function checkOrderData(orderData) {
            let items = orderData.items;
            for (let item of items) {
                if (!item.toolId) {
                    layer.msg('请选择工具');
                    return false;
                }
                if (!item.quantity) {
                    layer.msg('请填写数量');
                    return false;
                }
            }
            return true;
        }
    });
</script>
</body>
</html>